package com.bf.electroplating.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bf.electroplating.pojo.dto.RainfallSuspectedDischargeRequestDTO;
import com.bf.electroplating.pojo.dto.RainfallSuspectedDischargeResponseDTO;
import com.bf.electroplating.pojo.entity.RainfallOutletSite;
import com.bf.electroplating.pojo.entity.RainfallOutletSuspectedDischarge;
import com.bf.electroplating.service.IRainfallSuspectedDischargeSyncService;
import com.bf.electroplating.service.IRainfallOutletSiteService;
import com.bf.electroplating.service.IRainfallOutletSuspectedDischargeService;
import com.bf.electroplating.util.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 雨排口疑似偷排记录同步服务实现类
 *
 * @author system
 * @since 2025-01-11
 */
@Slf4j
@Service
public class RainfallSuspectedDischargeSyncServiceImpl implements IRainfallSuspectedDischargeSyncService {

    @Autowired
    private IRainfallOutletSiteService rainfallOutletSiteService;

    @Autowired
    private IRainfallOutletSuspectedDischargeService rainfallOutletSuspectedDischargeService;

    @Value("${company.api.baseUrl}")
    private String apiBaseUrl;

    @Value("${company.api.secret}")
    private String apiSecret;

    private final RestTemplate restTemplate = new RestTemplate();

    @Override
    public void syncAllSuspectedDischargeData() {
        log.info("开始同步所有站点的疑似偷排记录数据");
        try {
            // 获取所有站点
            List<RainfallOutletSite> sites = rainfallOutletSiteService.list();
            if (sites.isEmpty()) {
                log.warn("没有找到雨排口站点，请先同步站点数据");
                return;
            }
            // 为每个站点同步疑似偷排记录
            for (RainfallOutletSite site : sites) {
                try {
                    syncSuspectedDischargeDataBySiteId(site.getSiteId());
                } catch (Exception e) {
                    log.error("同步站点 {} 的疑似偷排记录失败", site.getSiteName(), e);
                }
            }
            log.info("所有站点疑似偷排记录数据同步完成");
        } catch (Exception e) {
            log.error("同步所有站点疑似偷排记录数据失败", e);
        }
    }

    @Override
    public void syncSuspectedDischargeDataBySiteId(Integer siteId) {
        log.info("开始同步站点 {} 的疑似偷排记录数据", siteId);
        try {
            // 构建请求参数
            RainfallSuspectedDischargeRequestDTO requestDTO = new RainfallSuspectedDischargeRequestDTO();
            requestDTO.setSiteId(siteId);
            requestDTO.setPage(1);
            requestDTO.setPageSize(100); // 每次获取100条记录

            // 调用外部API
            String response = callSuspectedDischargeAPI(requestDTO);
            
            // 解析响应数据
            RainfallSuspectedDischargeResponseDTO responseDTO = JSON.parseObject(response, RainfallSuspectedDischargeResponseDTO.class);
            
            if (responseDTO == null || !responseDTO.getSuccess() || responseDTO.getList() == null) {
                log.warn("站点 {} 的疑似偷排记录API返回失败或为空", siteId);
                return;
            }

            // 保存数据到数据库
            saveSuspectedDischargeData(siteId, responseDTO.getList());
            
            log.info("站点 {} 的疑似偷排记录数据同步完成，共处理 {} 条记录", 
                    siteId, responseDTO.getList().size());
        } catch (Exception e) {
            log.error("同步站点 {} 的疑似偷排记录数据失败", siteId, e);
        }
    }

    /**
     * 调用疑似偷排记录API
     */
    private String callSuspectedDischargeAPI(RainfallSuspectedDischargeRequestDTO requestDTO) {
        try {
            String url = apiBaseUrl + "/out/site/suspected/list";
            
            // 使用签名工具类的加密方法
            String encryptedParams = SignUtil.generateParams(requestDTO);
            
            log.debug("调用疑似偷排记录API: {}, 参数: {}", url, encryptedParams);
            
            // 发送POST请求
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/json");
            
            String response = restTemplate.postForObject(url, encryptedParams, String.class, headers);
            
            log.debug("疑似偷排记录API响应: {}", response);
            
            return response;
        } catch (Exception e) {
            log.error("调用疑似偷排记录API失败", e);
            throw new RuntimeException("调用疑似偷排记录API失败: " + e.getMessage());
        }
    }

    /**
     * 保存疑似偷排记录数据到数据库
     */
    private void saveSuspectedDischargeData(Integer siteId, List<RainfallSuspectedDischargeResponseDTO.SuspectedDischargeItem> dataList) {
        if (dataList == null || dataList.isEmpty()) {
            return;
        }

        // 获取站点信息
        RainfallOutletSite site = rainfallOutletSiteService.getOne(
                new LambdaQueryWrapper<RainfallOutletSite>()
                        .eq(RainfallOutletSite::getSiteId, siteId)
        );

        String siteName = site != null ? site.getSiteName() : "未知站点";

        // 转换并保存数据
        for (RainfallSuspectedDischargeResponseDTO.SuspectedDischargeItem item : dataList) {
            try {
                RainfallOutletSuspectedDischarge suspectedDischarge = new RainfallOutletSuspectedDischarge();
                suspectedDischarge.setSiteId(siteId);
                suspectedDischarge.setSiteName(siteName);
                
                // 解析时间段
                parseTimeRange(item.getVDate(), suspectedDischarge);
                
                // 设置数据值
                suspectedDischarge.setFactorMax(item.getVMax());
                suspectedDischarge.setFactorMin(item.getVMin());
                suspectedDischarge.setFactorAvg(item.getVAvg());
                
                // 计算超标比例（假设阈值为50，可根据实际情况调整）
                BigDecimal threshold = new BigDecimal("50");
                if (item.getVAvg() != null && threshold.compareTo(BigDecimal.ZERO) > 0) {
                    BigDecimal exceedRatio = item.getVAvg().subtract(threshold)
                            .divide(threshold, 4, java.math.RoundingMode.HALF_UP)
                            .multiply(new BigDecimal("100"));
                    suspectedDischarge.setExceedRatio(exceedRatio);
                }
                
                suspectedDischarge.setThresholdValue(threshold);
                suspectedDischarge.setIsVerified(false);
                
                // 检查是否已存在相同时间段的记录
                RainfallOutletSuspectedDischarge existingRecord = rainfallOutletSuspectedDischargeService.getOne(
                        new LambdaQueryWrapper<RainfallOutletSuspectedDischarge>()
                                .eq(RainfallOutletSuspectedDischarge::getSiteId, siteId)
                                .eq(RainfallOutletSuspectedDischarge::getSuspectedStartTime, suspectedDischarge.getSuspectedStartTime())
                                .eq(RainfallOutletSuspectedDischarge::getSuspectedEndTime, suspectedDischarge.getSuspectedEndTime())
                );

                if (existingRecord != null) {
                    // 更新现有记录
                    suspectedDischarge.setId(existingRecord.getId());
                    rainfallOutletSuspectedDischargeService.updateById(suspectedDischarge);
                } else {
                    // 插入新记录
                    rainfallOutletSuspectedDischargeService.save(suspectedDischarge);
                }
            } catch (Exception e) {
                log.error("保存疑似偷排记录失败: {}", item, e);
            }
        }

        log.info("成功保存站点 {} 的 {} 条疑似偷排记录", siteId, dataList.size());
    }

    /**
     * 解析时间段字符串
     * 格式：2025-09-10 12:00:00 ~ 2025-09-10 12:00:01
     */
    private void parseTimeRange(String timeRange, RainfallOutletSuspectedDischarge suspectedDischarge) {
        if (timeRange == null || !timeRange.contains(" ~ ")) {
            log.warn("时间段格式不正确: {}", timeRange);
            suspectedDischarge.setSuspectedStartTime(LocalDateTime.now());
            suspectedDischarge.setSuspectedEndTime(LocalDateTime.now());
            return;
        }

        try {
            String[] times = timeRange.split(" ~ ");
            if (times.length == 2) {
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                suspectedDischarge.setSuspectedStartTime(LocalDateTime.parse(times[0].trim(), formatter));
                suspectedDischarge.setSuspectedEndTime(LocalDateTime.parse(times[1].trim(), formatter));
            } else {
                log.warn("时间段格式不正确: {}", timeRange);
                suspectedDischarge.setSuspectedStartTime(LocalDateTime.now());
                suspectedDischarge.setSuspectedEndTime(LocalDateTime.now());
            }
        } catch (Exception e) {
            log.warn("解析时间段失败: {}", timeRange, e);
            suspectedDischarge.setSuspectedStartTime(LocalDateTime.now());
            suspectedDischarge.setSuspectedEndTime(LocalDateTime.now());
        }
    }
}
